package com.jushu.storbox.newfragment;

import java.util.Set;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Message;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jushu.storbox.CopyrightActivity;
import com.jushu.storbox.FolderBrowserActivity;
import com.jushu.storbox.InviteFriendActivity;
import com.jushu.storbox.LoginActivity;
import com.jushu.storbox.R;
import com.jushu.storbox.actions.SettingAction;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.MessageCode;
import com.jushu.storbox.handler.ClientExceptionRelateHandler;
import com.jushu.storbox.manager.ActivityTaskManager;
import com.jushu.storbox.manager.DownloadTaskManager;
import com.jushu.storbox.task.tqueue.DownloadTask;
import com.jushu.storbox.util.DirectoryUtil;
import com.jushu.storbox.util.PublicTools;
import com.jushu.storbox.view.dialog.ClouddriveDialog;
import com.jushu.storbox.view.viewImpl.SlipButton;
import com.jushu.storbox.view.viewImpl.SlipButton.OnChangedListener;
import com.huawei.sharedrive.sdk.android.modelV2.request.ClientInfoResponseV2;

public class SettingFragment extends AbsFrameFragment {

	private SlipButton downloadHint;

	private SlipButton autoLogin;

	private RelativeLayout clear_btn;

	private RelativeLayout cache_folder_btn;

	private Button unregister;

	private ProgressDialog myDialog;

	private TextView sdcardsize_tv;

	private TextView mShowUserTextView;

	private TextView version_tv;

	private TextView setting_cachepath_label;

	private RelativeLayout layout_version;

	private RelativeLayout layout_invite_friend;

	private RelativeLayout layout_copyright;

	private TextView tv_has_new_version;

	private ClientExceptionRelateHandler messageHandler;

	@Override
	protected int getTitleResourceId() {
		return R.layout.action_title_simple;
	}

	@Override
	protected int getContentResourceId() {
		return R.layout.frame_activity_setting;
	}

	@Override
	protected void startInitConpentData() {
	}

	@Override
	protected void onLoadTitleView(View titleView) {
		super.onLoadTitleView(titleView);
		TextView fragmentTitleName = (TextView) titleView.findViewById(R.id.fragmentTitleName);
		fragmentTitleName.setText(R.string.setting);
	}

	@Override
	protected void onLoadContentView(View contentView) {
		super.onLoadContentView(contentView);
		initView(contentView);
		initListenser();
		initHandler();
		loadCacheData();
	}

	private void loadCacheData() {
		new SettingAction().loadCacheSize(getMainFrameActivity(), messageHandler);
	}

	private void initView(View contentView) {
		downloadHint = (com.jushu.storbox.view.viewImpl.SlipButton) contentView.findViewById(R.id.downloadHint_sb);
		downloadHint.setCheck(PublicTools.getDownloadRemind(getMainFrameActivity()));
		autoLogin = (com.jushu.storbox.view.viewImpl.SlipButton) contentView.findViewById(R.id.autoLogin_sb);
		SharedPreferences settings = getMainFrameActivity().getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
		autoLogin.setCheck(settings.getBoolean(ClientConfig.AUTOLOGIN_SETTING, true));
		clear_btn =(RelativeLayout) contentView.findViewById(R.id.clear_btn);
		cache_folder_btn = (RelativeLayout) contentView.findViewById(R.id.cache_folder_btn);
		unregister = (Button) contentView.findViewById(R.id.unregister_btn);
		sdcardsize_tv = (TextView) contentView.findViewById(R.id.sdcardsize_tv);
		setting_cachepath_label = (TextView) contentView.findViewById(R.id.setting_cachepath_label);
		setting_cachepath_label.setText(DirectoryUtil.getCurrentCachePath(getMainFrameActivity()));
		version_tv = (TextView) contentView.findViewById(R.id.version_tv);
		version_tv.setText(getMainFrameActivity().getString(R.string.setting_app_version_text) + PublicTools.getVersionName(getMainFrameActivity()));
		mShowUserTextView = (TextView) contentView.findViewById(R.id.tv_show_user);
		mShowUserTextView.setText(PublicTools.getClientUserName(getMainFrameActivity()));
		layout_version = (RelativeLayout) contentView.findViewById(R.id.layout_version);
		layout_invite_friend = (RelativeLayout) contentView.findViewById(R.id.layout_invite_friend);
		layout_copyright = (RelativeLayout) contentView.findViewById(R.id.layout_copyright);
		tv_has_new_version = (TextView) contentView.findViewById(R.id.flag_has_new_version);
	}

	private void initListenser() {
		downloadHint.SetOnChangedListener(downloadHintListenser);
		autoLogin.SetOnChangedListener(autoLoginListenser);
		clear_btn.setOnClickListener(clearListenser);
		cache_folder_btn.setOnClickListener(cacheFolderListenser);
		unregister.setOnClickListener(unregisterListenser);
		layout_version.setOnClickListener(checkUpgradeListenser);
		layout_invite_friend.setOnClickListener(inviteFriendListener);
		layout_copyright.setOnClickListener(copyrightListener);
	}

	private void initHandler() {
		messageHandler = new ClientExceptionRelateHandler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MessageCode.VERSION_INFO_SUCCESS:
					// compare version, if need upgrade,then suggest user to
					// upgrade
					ClientInfoResponseV2 versionInfo = (ClientInfoResponseV2) msg.obj;
					new SettingAction().upgradeCloudDrive(getMainFrameActivity(), null, versionInfo, true);
					break;
				case MessageCode.LOGOUT_SUCCESS:

					myDialog.cancel();
//					Intent mHomeIntent = new Intent(Intent.ACTION_MAIN);
//
//					mHomeIntent.addCategory(Intent.CATEGORY_HOME);
//					mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
//					                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
					Intent intent = new Intent(getContext(), LoginActivity.class);
					startActivity(intent);
					getMainFrameActivity().finish();
//					try {
//
//
//
//					} finally {
//						getMainFrameActivity().startActivity(mHomeIntent);
//					}
					break;
				case MessageCode.LOAD_CACHE_SUCCESS:
					String[] sizeArray = (String[]) msg.obj;
					String cloudDriveSize = sizeArray[0];
					sdcardsize_tv.setText(getString(R.string.setting_space_downloaded_lable) + cloudDriveSize + ","
							+ getString(R.string.setting_space_available_lable) + sizeArray[1]);
					if ("0B".equals(cloudDriveSize) && clear_btn.isEnabled()) {
						clear_btn.setEnabled(false);
					}
					if (!"0B".equals(cloudDriveSize) && !clear_btn.isEnabled()) {
						clear_btn.setEnabled(true);
					}
					break;
				default:
					super.handleMessage(msg);
				}
			}

			@Override
			public Context getContext() {
				return getActivity();
			}
		};

	}

	private OnChangedListener downloadHintListenser = new OnChangedListener() {
		@Override
		public void OnChanged(boolean CheckState) {
			PublicTools.setDownloadRemind(getMainFrameActivity(), CheckState);
		}
	};

	private OnChangedListener autoLoginListenser = new OnChangedListener() {
		@Override
		public void OnChanged(boolean CheckState) {
			SharedPreferences settings = getMainFrameActivity().getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			Editor editor = settings.edit();
			editor.putBoolean(ClientConfig.AUTOLOGIN_SETTING, CheckState);
			if (CheckState) {
				editor.putBoolean(ClientConfig.AUTOLOGIN, CheckState);
				editor.putBoolean(ClientConfig.AUTOLOGIN_SETTING, CheckState);
			} else {
				editor.putBoolean(ClientConfig.AUTOLOGIN, CheckState);
				editor.putBoolean(ClientConfig.AUTOLOGIN_SETTING, CheckState);
			}
			editor.commit();
		}
	};

	private OnClickListener clearListenser = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			final ClouddriveDialog delete = new ClouddriveDialog(getMainFrameActivity(), R.style.dialog_upload, R.layout.dialog_filedelete);
			View conventView = delete.getConventView();
			WindowManager windowManager=getActivity().getWindowManager();
			Display display=windowManager.getDefaultDisplay();
			delete.setWidth(display.getWidth());
			delete.setPosition(Gravity.CENTER_HORIZONTAL, Gravity.CENTER_VERTICAL);
			Button dialog_cancal = (Button) conventView.findViewById(R.id.dialog_add_file_cancal_bt);
			Button dialog_OK = (Button) conventView.findViewById(R.id.dialog_add_file_ok_bt);

			TextView dialog_prompt_tv = (TextView) conventView.findViewById(R.id.dialog_prompt_tv);

			Set<DownloadTask> downloadTasks = DownloadTaskManager.getAllTaskes();
			if (downloadTasks != null && downloadTasks.size() > 0) {
				dialog_prompt_tv.setText(getMainFrameActivity().getString(R.string.setting_clear_downloading));
			} else {
				dialog_prompt_tv.setText(getMainFrameActivity().getString(R.string.setting_activity_quest_comfirm_clear_cache));
			}
			dialog_cancal.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					delete.dismiss();
				}
			});

			dialog_OK.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					delete.dismiss();
					new SettingAction().clearCloudDriveCache(getMainFrameActivity(), messageHandler);
				}
			});
			delete.show();
		}
	};

	private OnClickListener cacheFolderListenser = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			Intent intent = new Intent();
			intent.setClass(getMainFrameActivity(), FolderBrowserActivity.class);
			startActivityForResult(intent, 5);
		}
	};

	private OnClickListener inviteFriendListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent = new Intent(getActivity(), InviteFriendActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		}
	};

	private OnClickListener copyrightListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent = new Intent(getActivity(), CopyrightActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		}
	};

	/**
	 * SettingActivity layout out Listener
	 */
	private OnClickListener unregisterListenser = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			final ClouddriveDialog unregisterDialog = new ClouddriveDialog(getMainFrameActivity(), R.style.dialog_upload, R.layout.dialog_logout_new);
			//unregisterDialog.show();
			View conventView = unregisterDialog.getConventView();
			Button confirm_btn = (Button) conventView.findViewById(R.id.confirm_btn);
			Button cancle_btn = (Button) conventView.findViewById(R.id.cancle_btn);
			WindowManager windowManage=getActivity().getWindowManager();
			Display display=windowManage.getDefaultDisplay();
			unregisterDialog.setWidth(display.getWidth());
			unregisterDialog.setPosition(Gravity.CENTER_HORIZONTAL, Gravity.CENTER_VERTICAL);
			confirm_btn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					myDialog = new ProgressDialog(getMainFrameActivity());
					myDialog.setMessage(getMainFrameActivity().getString(R.string.setting_activity_logouting));
					myDialog.show();
					myDialog.setCanceledOnTouchOutside(false);
					unregisterDialog.dismiss();

					new SettingAction().logout(getMainFrameActivity(), messageHandler);
					// if (shareDriveService != null) {
					// shareDriveService.destoryMusicplayer();
					// }
				}
			});
			cancle_btn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					unregisterDialog.dismiss();
				}
			});
			unregisterDialog.show();
		}
	};

	private OnClickListener checkUpgradeListenser = new OnClickListener() {
		@Override
		public void onClick(View v) {
			new SettingAction().getVersionInfo(getMainFrameActivity(), messageHandler);
		}
	};

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {
		case MessageCode.RESULT_CODE_CACHE_FOLDER:
			String mCurrentDir = data.getBundleExtra("result").getString("mCurrentDir");
			setting_cachepath_label.setText(mCurrentDir);
			break;
		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);

	}

}
